/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.scalia.meteocal.control;


import com.scalia.meteocal.entity.Event;
import com.scalia.meteocal.entity.Group;
import com.scalia.meteocal.entity.User;
import java.security.Principal;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author gabriele
 */
@Stateless
public class UserManager {
    
    public UserManager() {

    }

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;

    public void save(User user) {
        user.setGroupName(Group.USERS);
        em.persist(user);
    }
    
    public boolean checkIfUserExist(User user) {
        return em.find(User.class, user.getUsername()) != null;
    }
    
    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        return em.find(User.class, principal.getName());
    }
    
    public List<User> getAllUsers() {
        Query query = em.createNamedQuery(User.findAll);
        return query.getResultList();
    }
    
    public List<User> getAllUserExceptSelf() {
        Query query = em.createNamedQuery(User.findAllExceptOne).setParameter("exceptUser", em.find(User.class, principal.getName()));
        return query.getResultList();
    }
    
    public List<String> getAllUsernames() {
        Query query = em.createNamedQuery(User.findAllUsernames);
        return query.getResultList();       
    }
    
    public List<String> getAllUsernamesExceptSelf() {
        Query query = em.createNamedQuery(User.findAllUsernamesExceptOne).setParameter("exceptUser", em.find(User.class, principal.getName()));
        return query.getResultList();    
    }
    
    public List<User> getAllPartecipantsToEvent(Event event) {
        Query query = em.createNamedQuery(User.findAllPartecipantsToEvent).setParameter("event", event);
        return query.getResultList();
    }
}
